package ctrLayer;

import java.io.*;
import java.util.ArrayList;

import modelLayer.Flavour;
import modelLayer.FlavourContainer;
import modelLayer.PresetContainer;

public class PresetCtr {
	private PresetContainer pCont;
	
	public PresetCtr(){
		pCont = PresetContainer.getInstance();
	}
	
	public void addPreset(ArrayList<Flavour> preset){
		pCont.addPreset(preset);
	}
	
	public void loadPreset(int id) throws NullPointerException{
		ArrayList<Flavour> preset = pCont.getPreset(id);
		if(preset != null){
			GraphCtr gCtr = new GraphCtr();
			gCtr.clear();
			for(Flavour f : preset){
				gCtr.addToGraph(f.getFlavour());
			}
		}else{
			throw new NullPointerException("That Preset does not exist!");
		}
	}
	
	public void save() throws IOException{
		Writer writer = null;
		String nL = System.getProperty("line.separator");
		ArrayList<ArrayList<Flavour>> presets = pCont.getPresets();
		if(presets != null){
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./preset.txt"), "UTF-8"));
			for(ArrayList<Flavour> preset : presets){
				String wString = "";
				for(Flavour f : preset){
					wString += f.getId() + ",";
				}
				writer.write(wString.substring(0, wString.length()-1) + nL);
			}
			writer.close();
		}
	}
	
	public void load() throws IOException{
		BufferedReader bf = new BufferedReader(new FileReader(new File("./preset.txt")));
		FlavourContainer fCont = FlavourContainer.getInstance();
		String line;
		while((line = bf.readLine()) != null){
			ArrayList<Flavour> preset = new ArrayList<Flavour>();
			String[] tokens = line.split(",");
			for(String s : tokens){
				preset.add(fCont.getFlavour(Integer.parseInt(s)));
			}
			pCont.addPreset(preset);
		}
		bf.close();
	}
	
	public boolean saveExist(){
		boolean ret = false;
		File f = new File("./preset.txt");
		if(f.exists() && !f.isDirectory()){
			ret = true;
		}
		return ret;
	}
	
	public ArrayList<ArrayList<Flavour>> getPresets(){
		return pCont.getPresets();
	}
	
	public void removePreset(int id) throws IndexOutOfBoundsException{
		pCont.removePreset(id);
	}
	
	public ArrayList<Flavour> getPreset(int id){
		return pCont.getPreset(id);
	}

}
